/**
 * Created by zhanglihe on 15/11/4.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'bootstrap',
    'collection',
    'template',
    'fineuploader'
], function ($, common, ready, bootstrap, Collection, template, Uploader) {

    var index = function () {
        this.init();
    };

    //是否开启多图上传
    var multiple = getUrlPara('multiple') ? true : false;

    //已选图片集合(供父窗口调用)
    window.image = {
        data: {},
        set: function (id, val) {
            if (multiple) {
                this.data[id] = val;
            } else {
                this.data = val;
            }
        },
        get: function () {
            return this.data;
        },
        del: function (id) {
            if (multiple) {
                delete this.data[id];
            } else {
                this.data = {};
            }
        },
        clear: function () {
            this.data = {};
        }
    };

    index.prototype = {
        init: function () {
            this.upload();
            this.loadImage();
            this.event();
        },
        upload: function () {
            var that = this;
            $('#upload-view').html(template('upload-tpl'));

            var _path = typeof img_path !== 'undefined' ? img_path : '';
            //上传相关
            $("#J_UploadImgs").fineUploader({
                request: {
                    endpoint: window._global.url.api + 'attachment/upload',
                    inputName: 'filedata',
                    params: {
                        access_token: window._global.access_token,
                        folder: _path
                    }
                },
                multiple: multiple,
                deleteFile: {
                    enabled: true,
                    endpoint: window._global.url.api + 'attachment'
                },
                callbacks: {
                    onProgress: function (id, filename, loaded, total) {
                        var progress = parseInt(loaded / total * 100, 10);
                        //$('#qq-file-id-'+id+' .upload-progress-bar').css('width',progress+ '%');
                        $('#img-view-' + id).html('进度：' + progress + '%')
                    },
                    onSubmit: function (id, filename) {
                        $('#J_ImgList').append('<li class="upload-loading" id="img-view-' + id + '">正在上传中...</li>');
                    }
                }
            }).on('complete', function (event, id, fileName, response) {
                if (response.success) {
                    var imgItem = $(template('img-item-tpl', response.data));
                    imgItem.on('click', function (e) {
                        //单图下，只能选一
                        if (!multiple) {
                            $('#J_ImgList').find('.p-img').removeClass('selected');
                        }
                        if ($(this).hasClass('selected')) {
                            window.image.del(response.data.id);
                            $(this).removeClass('selected');
                        } else {
                            window.image.set(response.data.id, {id: response.data.id, fileUrl: response.data.fileUrl});
                            $(this).addClass('selected');
                        }
                    });
                    $('#img-view-' + id).replaceWith(imgItem);
                    window.image.set(response.data.id, {id: response.data.id, fileUrl: response.data.fileUrl});
                    imgItem.addClass('selected');
                    !multiple && $('.qq-upload-button-selector').hide();
                } else {
                    $('#img-view-' + id).hide();
                    alert(response.msg);
                }
            });

            $('#J_ImgList').on('click', '.J_Delete', function () {
                var _$item = $(this).parents('li')
                    , img_id = _$item.attr('data-id');
                $.ajax({
                    async: false,
                    url: window._global.url.api + 'attachment/' + img_id,
                    type: 'DELETE',
                    success: function (response) {
                        _$item.remove();
                        !multiple && $('.qq-upload-button-selector').show();
                    }
                });
            });
        },

        loadImage: function () {
            var that = this;
            //加载列表
            $('#image-view').html(template('album-tpl'));
            new Collection({
                url: window._global.url.api + 'attachments',
                condition: {
                    'limit': 8,
                    'offset': 0
                },
                page: {page_max: 6, page_size: 8, current_page: 1},
                model: {
                    tag_name: 'div',
                    class_name: 'col-xs-3 col-lg-2 img-box',
                    event: {
                        '.thumbnail img:click': 'selectImage'
                    },
                    //选择/反选图片
                    selectImage: function (e) {
                        var model = this;
                        e.preventDefault();
                        //单图下，只能选一
                        if (!multiple) {
                            $('.thumbnail').removeClass('selected');
                        }
                        if ($(e.target).parent().hasClass('selected')) {
                            window.image.del(model.data.id);
                            $(e.target).parent().removeClass('selected');
                        } else {
                            window.image.set(model.data.id, {id: model.data.id, fileUrl: model.data.file_url});
                            $(e.target).parent().addClass('selected');
                        }
                    }
                }
            }).fetch();
        },

        event: function () {
            var _this = this;
            //tab事件
            $('.nav-tabs').find('a').on('click', function (e) {
                e.preventDefault();
                $(this).parent().addClass('active').siblings().removeClass('active');
                if ($(this).attr('rel') == 'upload') {
                    $('#upload-view').show();
                    $('#image-view').hide();
                }
                if ($(this).attr('rel') == 'album') {
                    $('#upload-view').hide();
                    $('#image-view').show();
                }
            });
        }
    };

    new index();

});